//
//  mineLoginMailVC.m
//  AroundTheWorld
//
//  Created by dllo on 16/5/27.
//  Copyright © 2016年 IfelseGo an. All rights reserved.
//

#import "mineLoginMailVC.h"
#import "MineLoginVC.h"
#import "MineRegisterMailVC.h"
#import "DataBaseHandle.h"

typedef enum { Valid, UserNameEmpty, InvalidPasswordError} LoginResult;

@interface NSString (Validation)

+ (BOOL)isEmpty:(NSString *)string;

@end

@implementation NSString (Validation)

+ (BOOL)isEmpty:(NSString *)string;
{
    if (string == nil) {
        return YES;
    }
    
    if (string.length == 0) {
        return YES;
    }
    
    return NO;
}

@end


@interface mineLoginMailVC ()

@end

@implementation mineLoginMailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.view.backgroundColor = [UIColor colorWithRed:76 / 255.0 green:197 / 255.0 blue:143 / 255.0 alpha:1.0];
    
    self.passTextF.secureTextEntry = YES;
    self.zhuceButton.layer.borderColor = [[UIColor whiteColor] CGColor];
    //手机号码登录
    [self.phoneButton addTarget:self action:@selector(phoneButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //返回按钮
    [self.fanhuiButton addTarget:self action:@selector(fanhuiButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //注册按钮
    [self.zhuceButton addTarget:self action:@selector(zhuceButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //登录按钮
    [self.dengluButton addTarget:self action:@selector(dengluButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //新浪登录
    [self.XLButton addTarget:self action:@selector(XLButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
 }
//返回按钮
- (void)fanhuiButtonAction:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
//手机号登录
- (void)phoneButtonAction:(UIButton *)button
{
    MineLoginVC *loginVC = [[MineLoginVC alloc] initWithNibName:@"MineLoginVC" bundle:nil];
    [self presentViewController:loginVC animated:YES completion:^{
        
        
    }];
}
//新浪登录
- (void)XLButtonAction
{
    //登录第二步
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
    snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        //          获取微博用户名、uid、token等
         if (response.responseCode == UMSResponseCodeSuccess) {//登录成功
            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary] valueForKey:UMShareToSina];
            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);
             
             //保存数据到 用户名和密码字典里
             
             //用户名不存在
             NSMutableArray *userArray = [[DataBaseHandle shareDataBaseHandle] selectAllWithSQname:@"users" withCompare:YES];
             self.reModel = [[MineRegidterModel alloc] init];
             self.reModel.userID = snsAccount.userName;
             self.reModel.password = @"";
             self.reModel.pic = snsAccount.iconURL;
             if (![userArray containsObject:snsAccount.userName]) {
                 [[DataBaseHandle shareDataBaseHandle] insertMovie:self.reModel withSQname:@"users"];
             }
      
             NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
             [data setObject:self.reModel.userID forKey:@"userName"];
             [data setObject:self.reModel.pic forKey:@"userPic"];
             [self addValid];
             
             //登录第三步 ：在登录成功后 获取用户信息
             //获取accestoken以及新浪用户信息，得到的数据在回调Block对象形参respone的data属性
            [[UMSocialDataService defaultDataService] requestSnsInformation:UMShareToSina  completion:^(UMSocialResponseEntity *response){
                NSLog(@"SnsInformation is %@",response.data);

            }];
         }});
}

//注册按钮
- (void)zhuceButtonAction:(UIButton *)button
{
    MineRegisterMailVC *registVC = [[MineRegisterMailVC alloc] initWithNibName:@"MineRegisterMailVC" bundle:nil];
    [self presentViewController:registVC animated:YES completion:^{
        
    }];
}

//登录按钮
- (void)dengluButtonAction:(UIButton *)button
{
    LoginResult result = [self canLogin];
    if (result != Valid) {
        // show alert with result
        switch (result) {
            case UserNameEmpty:
                [self addAlertControllerWithTitle:@"登录失败" withMessage:@"用户名不存在!"];
                break;
            case InvalidPasswordError:
                [self addAlertControllerWithTitle:@"登录失败" withMessage:@"密码错误!"];
                break;
            default:
                break;
        }
        return;
    }
    [self login];
 
}
//用户名空时返回
- (LoginResult)canLogin {
    // panduan user name
    NSString *idText = self.mailTextF.text;
    NSString *pass = self.passTextF.text;
    
    if ([NSString isEmpty:idText]) {
        return UserNameEmpty;
    }
    //用户名不存在
    NSMutableArray *userArray = [[DataBaseHandle shareDataBaseHandle] selectAllWithSQname:@"users" withCompare:YES];
    NSMutableArray *allArray = [[DataBaseHandle shareDataBaseHandle] selectAllWithSQname:@"users" withCompare:NO];
    if (![userArray containsObject:idText]) {
        return UserNameEmpty;
    }
    //密码确认
    for (MineRegidterModel *model in allArray) {
        if ([model.userID isEqualToString:idText]) {
            if (![model.password isEqualToString:pass]) {
                return InvalidPasswordError;
            }
        }
    }
    return Valid;
}
//当前登陆者用户名
- (void)login {
    NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
    [data setObject:self.mailTextF.text forKey:@"userName"];
    [data setObject:@"http://tva2.sinaimg.cn/crop.0.0.180.180.180/5e300a5ajw1e8qgp5bmzyj2050050aa8.jpg" forKey:@"userPic"];
    [self addValid];
}
// Error  AlertController
-(void)addAlertControllerWithTitle:(NSString *)acTitle withMessage:(NSString *)message
{
    UIAlertController * alertC = [UIAlertController alertControllerWithTitle:acTitle message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel  handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertC addAction:cancelAction];
    //运行
    [self presentViewController:alertC animated:YES completion:^{
        
    }];
}
-(void)addValid{
    //创建
    UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"登录成功" message:@"返回用户页面!" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaltAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }];
    [alertC addAction:defaltAction];
    [self presentViewController:alertC animated:YES completion:^{
        
    }];
}

//点击空白处收回键盘
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.mailTextF resignFirstResponder];
    [self.passTextF resignFirstResponder];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
